package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.PurchaseService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemDoneVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();

        String status = (String) params.get("status");
        if(StringUtils.isNotEmpty(status)){
            wrapper.eq("status",status);
        }
        String key = (String)params.get("key");
        if(StringUtils.isNotEmpty(key)){
            wrapper.and(wrapper1->{
                wrapper1.like("assignee_name",key).or().eq("id",key);
            });
        }
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    //查询 未分配的采购单
    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {


        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );

        return new PageUtils(page);
    }

    //合并采购单
    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();

        if(purchaseId==null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();

            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseEnum.CREATED.getCode());

            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //合并采购需求 其实就是将更新采购需求的采购单id，状态更新为已分配
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailEnum.ASSIGNED.getCode());

            return purchaseDetailEntity;

        }).collect(Collectors.toList());


    purchaseDetailService.updateBatchById(collect);

    //更新 更新时间字段
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(finalPurchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }

    //采购员领取采购单
    @Transactional
    @Override
    public void receive(List<Long> ids) {
        //1. 确定当前采购单是新建或者已分配状态

        List<PurchaseEntity> collect = ids.stream().map(item -> {
            PurchaseEntity byId = this.getById(item);
            return byId;
        }).filter(item -> {
            if (item.getStatus()==WareConstant.PurchaseEnum.CREATED.getCode()||item.getStatus()==WareConstant.PurchaseEnum.ASSIGNED.getCode()){
                return true;
            }
            return false;
        }).map(item->{
            item.setStatus(WareConstant.PurchaseEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;

        }).collect(Collectors.toList());
        System.out.println(collect);

        //改变采购单的状态
        this.updateBatchById(collect);

        //改变采购项的状态
      collect.forEach((item)->{
          List<PurchaseDetailEntity> purchaseDetailEntities =  purchaseDetailService.listDetailByPurchaseId(item.getId());
          List<PurchaseDetailEntity> collect2 = purchaseDetailEntities.stream().map(item2 -> {
              PurchaseDetailEntity entity = new PurchaseDetailEntity();
              entity.setStatus(WareConstant.PurchaseDetailEnum.BUYING.getCode());
              entity.setId(item2.getId());
              return entity;
          }).collect(Collectors.toList());

          purchaseDetailService.updateBatchById(collect2);

      });
    }

    //完成采购
    @Transactional
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        Long id = purchaseDoneVo.getId();

        Boolean flag = true;
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        List<PurchaseDetailEntity> updates =new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if(item.getStatus()==WareConstant.PurchaseDetailEnum.HASERROR.getCode()){
                flag = false;
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailEnum.HASERROR.getCode());
            }else{
                //采购正常
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailEnum.Finish.getCode());
                //将完成的进行入库
                PurchaseDetailEntity byId = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(byId.getSkuId(),byId.getWareId(),byId.getSkuNum());

            }
            purchaseDetailEntity.setId(item.getItemId());
            updates.add(purchaseDetailEntity);

        }
        System.out.println(updates);

        purchaseDetailService.updateBatchById(updates);

        //改变采购单的状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseEnum.Finish.getCode() : WareConstant.PurchaseEnum.HASERROR.getCode());

        this.updateById(purchaseEntity);

    }

}